package com.example.kafka.controller;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.example.kafka.service.TransactionRiskyService;

import lombok.extern.slf4j.Slf4j;

/**
 * 有数据不一致风险的控制器示例
 * 演示多个数据库操作未在事务中执行导致的数据不一致问题
 */
@Slf4j
@RestController
@RequestMapping("/api/transaction/risky")
public class TransactionRiskyController {

    @Autowired
    private TransactionRiskyService transactionRiskyService;

    /**
     * 风险示例1：创建用户和账户（无事务保护）
     * GET
     * /api/transaction/risky/create-user-account?username=test&email=test@example.com&fullName=Test
     * User
     */
    @GetMapping("/create-user-account")
    public ResponseEntity<String> createUserWithAccount(
            @RequestParam String username,
            @RequestParam String email,
            @RequestParam String fullName) {

        log.info("请求创建用户和账户（无事务保护）: {}", username);

        try {
            String result = transactionRiskyService.createUserWithAccountRisky(username, email, fullName);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("创建用户和账户失败: {}", e.getMessage());
            return ResponseEntity.internalServerError().body("创建失败: " + e.getMessage());
        }
    }

    /**
     * 风险示例2：转账操作（无事务保护）
     * GET /api/transaction/risky/transfer?fromUserId=1&toUserId=2&amount=100.00
     */
    @GetMapping("/transfer")
    public ResponseEntity<String> transferMoney(
            @RequestParam Long fromUserId,
            @RequestParam Long toUserId,
            @RequestParam BigDecimal amount) {

        log.info("请求转账操作（无事务保护）: 从用户{}转账{}到用户{}", fromUserId, amount, toUserId);

        try {
            String result = transactionRiskyService.transferMoneyRisky(fromUserId, toUserId, amount);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("转账操作失败: {}", e.getMessage());
            return ResponseEntity.internalServerError().body("转账失败: " + e.getMessage());
        }
    }

    /**
     * 风险示例3：批量更新用户状态（无事务保护）
     * POST /api/transaction/risky/batch-update-status
     * Body: {"userIds": [1, 2, 3], "newStatus": "INACTIVE"}
     */
    @PostMapping("/batch-update-status")
    public ResponseEntity<String> batchUpdateUserStatus(
            @RequestBody BatchUpdateRequest request) {

        log.info("请求批量更新用户状态（无事务保护）: {} 个用户", request.getUserIds().size());

        try {
            String result = transactionRiskyService.batchUpdateUserStatusRisky(
                    request.getUserIds(), request.getNewStatus());
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("批量更新用户状态失败: {}", e.getMessage());
            return ResponseEntity.internalServerError().body("批量更新失败: " + e.getMessage());
        }
    }

    /**
     * 风险示例4：复杂业务操作（无事务保护）
     * GET /api/transaction/risky/complex-operation?userId=1&amount=50.00
     */
    @GetMapping("/complex-operation")
    public ResponseEntity<String> complexBusinessOperation(
            @RequestParam Long userId,
            @RequestParam BigDecimal amount) {

        log.info("请求复杂业务操作（无事务保护）: 用户{}, 金额{}", userId, amount);

        try {
            String result = transactionRiskyService.complexBusinessOperationRisky(userId, amount);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("复杂业务操作失败: {}", e.getMessage());
            return ResponseEntity.internalServerError().body("复杂业务操作失败: " + e.getMessage());
        }
    }

    /**
     * 演示数据不一致问题的测试接口
     * GET /api/transaction/risky/demo-data-inconsistency
     */
    @GetMapping("/demo-data-inconsistency")
    public ResponseEntity<String> demoDataInconsistency() {
        log.info("开始演示数据不一致问题");

        StringBuilder result = new StringBuilder();
        result.append("=== 数据不一致风险演示 ===\n\n");

        // 演示1：创建用户和账户
        result.append("1. 创建用户和账户（无事务保护）:\n");
        try {
            String createResult = transactionRiskyService.createUserWithAccountRisky(
                    "risky_user_" + System.currentTimeMillis(),
                    "risky@example.com",
                    "Risky User");
            result.append("   结果: ").append(createResult).append("\n");
        } catch (Exception e) {
            result.append("   结果: 失败 - ").append(e.getMessage()).append("\n");
        }

        result.append("\n2. 转账操作（无事务保护）:\n");
        try {
            String transferResult = transactionRiskyService.transferMoneyRisky(1L, 2L, new BigDecimal("100.00"));
            result.append("   结果: ").append(transferResult).append("\n");
        } catch (Exception e) {
            result.append("   结果: 失败 - ").append(e.getMessage()).append("\n");
        }

        result.append("\n3. 批量更新状态（无事务保护）:\n");
        try {
            String batchResult = transactionRiskyService.batchUpdateUserStatusRisky(
                    Arrays.asList(1L, 2L, 3L), "INACTIVE");
            result.append("   结果: ").append(batchResult).append("\n");
        } catch (Exception e) {
            result.append("   结果: 失败 - ").append(e.getMessage()).append("\n");
        }

        result.append("\n=== 风险说明 ===\n");
        result.append("- 如果任何步骤失败，已执行的步骤不会回滚\n");
        result.append("- 可能导致用户记录残留、资金丢失、状态不一致等问题\n");
        result.append("- 建议使用事务管理来确保数据一致性\n");

        return ResponseEntity.ok(result.toString());
    }

    /**
     * 请求体类
     */
    public static class BatchUpdateRequest {
        private List<Long> userIds;
        private String newStatus;

        public List<Long> getUserIds() {
            return userIds;
        }

        public void setUserIds(List<Long> userIds) {
            this.userIds = userIds;
        }

        public String getNewStatus() {
            return newStatus;
        }

        public void setNewStatus(String newStatus) {
            this.newStatus = newStatus;
        }
    }
}
